/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.documents.main.action;

import com.documents.common.core.PageBean;
import com.documents.common.core.action.BaseActionSupport;
import com.documents.common.util.FileStorage;
import com.documents.common.util.FileUtility;
import com.documents.common.util.StringUtil;
import com.documents.htmlobj.CountryObj;
import com.documents.htmlobj.ProductObj;
import com.documents.pojo.Accessory;
import com.documents.pojo.Case;
import com.documents.pojo.CaseFillPoints;
import com.documents.pojo.Country;
import com.documents.pojo.Document;
import com.documents.pojo.Product;
import com.documents.service.cas.CaseFillPointsService;
import com.documents.service.cas.CaseService;
import com.documents.service.country.CountryService;
import com.documents.service.document.DocumentFormatOrderService;
import com.documents.service.document.DocumentIndexTreeService;
import com.documents.service.document.DocumentService;
import com.documents.service.product.ProductService;
import com.documents.service.updown.FileUpDownService;

import java.io.File;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Timestamp;
import java.util.List;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.interceptor.ServletRequestAware;

/**
 *
 * @author sunying
 */
public class CaseAction extends BaseActionSupport implements ServletRequestAware {

    //private Document document;
    private Country contry;
    private Case ca;
    private Product product;
    private int page = 1;
    private PageBean pageBean;
    private int pageSize = 20;
    private List<Country> countryList;
    private List<Product> productList;
    private List<ProductObj> proList;
    private List<Accessory> accessoryList;
    private List<Document> documentList;
    private int caseId;
    private String startTime;
    private String endTime;
    private CaseFillPointsService casePointsService;
    private CaseFillPoints casePoints;
    private int casePointId;
    private List<CaseFillPoints> casefillpointsList;
    private static String CASEFILLPOINTS = "case_fill_points";
    private String delstrings;
    private DocumentIndexTreeService documentIndexTreeService;

    public DocumentIndexTreeService getDocumentIndexTreeService() {
        return documentIndexTreeService;
    }

    public void setDocumentIndexTreeService(DocumentIndexTreeService documentIndexTreeService) {
        this.documentIndexTreeService = documentIndexTreeService;
    }

    public List<ProductObj> getProList() {
        return proList;
    }

    public void setProList(List<ProductObj> proList) {
        this.proList = proList;
    }

    public String getDelstrings() {
        return delstrings;
    }

    public void setDelstrings(String delstrings) {
        this.delstrings = delstrings;
    }

    public List<CaseFillPoints> getCasefillpointsList() {
        return casefillpointsList;
    }

    public void setCasefillpointsList(List<CaseFillPoints> casefillpointsList) {
        this.casefillpointsList = casefillpointsList;
    }

    public String getEndTime() {
        return this.endTime;
    }

    public void setEndTime(String endTime) {
        this.endTime = endTime;
    }

    public String getStartTime() {
        return this.startTime;
    }

    public void setStartTime(String startTime) {
        this.startTime = startTime;
    }

    public int getCaseId() {
        return caseId;
    }

    public void setCaseId(int caseId) {
        this.caseId = caseId;
    }
    private String docIdString;//单证名称的组合
    private CountryService countryService;
    private ProductService productService;
    private CaseService caseService;
    private DocumentService documentService;
    private FileUpDownService fileUpDownService;
    private DocumentFormatOrderService documentFromatOrderService;
//    
    private File[] file;
    private String[] fileName;
    private String dlFileName;
    private String trueName;
    private String actionURI;
    private static String DOCUMENT = "case";

    public CaseService getCaseService() {
        return this.caseService;
    }

    public void setCaseService(CaseService caseService) {
        this.caseService = caseService;
    }

    public List<Document> getDocumentList() {
        return this.documentList;
    }

    public void setDocumentList(List<Document> documentList) {
        this.documentList = documentList;
    }

    public String add_input() {
        actionURI = "save";
        this.createMenus();
        return SUCCESS;
    }

    public static String getDOCUMENT() {
        return DOCUMENT;
    }

    public static void setDOCUMENT(String DOCUMENT) {
        CaseAction.DOCUMENT = DOCUMENT;
    }

    public List<Accessory> getAccessoryList() {
        return accessoryList;
    }

    public void setAccessoryList(List<Accessory> accessoryList) {
        this.accessoryList = accessoryList;
    }

    public String getActionURI() {
        return actionURI;
    }

    public void setActionURI(String actionURI) {
        this.actionURI = actionURI;
    }

    public Case getCa() {
        return this.ca;
    }

    public void setCa(Case ca) {
        this.ca = ca;
    }

    public Country getContry() {
        return this.contry;
    }

    public void setContry(Country contry) {
        this.contry = contry;
    }

    public List<Country> getCountryList() {
        return countryList;
    }

    public void setCountryList(List<Country> countryList) {
        this.countryList = countryList;
    }

    public CountryService getCountryService() {
        return countryService;
    }

    public void setCountryService(CountryService countryService) {
        this.countryService = countryService;
    }

    public String getDlFileName() {
        return this.dlFileName;
    }

    public void setDlFileName(String dlFileName) {
        this.dlFileName = dlFileName;
    }

    public DocumentFormatOrderService getDocumentFromatOrderService() {
        return this.documentFromatOrderService;
    }

    public void setDocumentFromatOrderService(DocumentFormatOrderService documentFromatOrderService) {
        this.documentFromatOrderService = documentFromatOrderService;
    }

    public File[] getFile() {
        return file;
    }

    public void setFile(File[] file) {
        this.file = file;
    }

    public String[] getFileName() {
        return fileName;
    }

    public void setFileName(String[] fileName) {
        this.fileName = fileName;
    }

    public FileUpDownService getFileUpDownService() {
        return fileUpDownService;
    }

    public void setFileUpDownService(FileUpDownService fileUpDownService) {
        this.fileUpDownService = fileUpDownService;
    }

    public DocumentService getDocumentService() {
        return this.documentService;
    }

    public void setDocumentService(DocumentService documentService) {
        this.documentService = documentService;
    }

    public String selectDocument() throws Exception {

        this.documentList = documentService.getDocumentList();

        return SUCCESS;
    }

    public int getPage() {
        return page;
    }

    public void setPage(int page) {
        this.page = page;
    }

    public PageBean getPageBean() {
        return pageBean;
    }

    public void setPageBean(PageBean pageBean) {
        this.pageBean = pageBean;
    }

    public int getPageSize() {
        return pageSize;
    }

    public void setPageSize(int pageSize) {
        this.pageSize = pageSize;
    }

    public Product getProduct() {
        return product;
    }

    public void setProduct(Product product) {
        this.product = product;
    }

    public List<Product> getProductList() {
        return productList;
    }

    public void setProductList(List<Product> productList) {
        this.productList = productList;
    }

    public ProductService getProductService() {
        return productService;
    }

    public void setProductService(ProductService productService) {
        this.productService = productService;
    }

    public String getTrueName() {
        return trueName;
    }

    public void setTrueName(String trueName) {
        this.trueName = trueName;
    }

    public String list() {
        pageBean = caseService.getPageBean(page, pageSize, ca, startTime, endTime);
        this.createMenus();
        return SUCCESS;
    }

    public String save() {
        if (ca != null) {
//            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
//            ca.setTime(timestamp);
            String num = StringUtil.getRequestNo();
            ca.setNum(num);
            if (ca.getProduct() > -1) {
                Product p = productService.get(ca.getProduct());
                if (p != null) {
                    ca.setProductName(p.getName());
                    ca.setProductCode(p.getCode());
                }
            }
            if (ca.getCountry() > -1) {
                Country c = countryService.get(ca.getCountry());
                if (c != null) {
                    ca.setCountryName(c.getName());
                    ca.setCountryCode(c.getCode());
                }
            }
            caseService.saveInstance(ca, docIdString);
            return SUCCESS;

        } else {

            addActionMessage("dc is null!");
            return ERROR;
        }

    }

    public void fileUpload(CaseFillPoints dt) {
        // public void fileUpload(Object obj) {
        System.out.println("文件大小" + this.getFile().length);
        System.out.println("文件有" + this.getFile());

        fileName = fileName[0].toString().split("%");
        for (int i = 0; i < this.getFile().length; i++) {
            String name = StringUtil.generateFileName(fileName[i + 1]);
            dt.setCasepoint(name);
//            name=name.substring(0, name.indexOf("."));
            String tmpurl = "/document/" + name;
            String url = FileStorage.getUpLoadPath(ServletActionContext.getRequest())
                    + tmpurl;

            File dstFile = new File(url);
            try {
                FileUtils.forceMkdir(dstFile.getParentFile());
            } catch (IOException e) {
                logger.error("创建文件失败！");
                e.printStackTrace();
            }// 创建上传tempFile文件所在的父目录文件;
            System.out.println("文件路径" + dstFile);
            FileUtility.copy(file[i], dstFile);
            Accessory accessory = new Accessory();
            accessory.setName(name);
            accessory.setTruename(fileName[i + 1]);
//            if(obj instanceof Case)
//            {
//                Case dt = (Case)obj;
//                accessory.setTableId(dt.getId());
//                accessory.setTableName("case");
//            }

            accessory.setTableId(dt.getId());
            accessory.setTableName("case_fill_points");

            Timestamp timestamp = new Timestamp(System.currentTimeMillis());
            accessory.setUploadDate(timestamp);
            accessory.setUrl(tmpurl);

            fileUpDownService.addUpFileInfo(accessory);
        }

    }

    public String down() throws Exception {

        try {
            String url = FileStorage.getUpLoadPath(ServletActionContext.getRequest()) + "/document/" + this.dlFileName;

//            String url = ServletActionContext.getServletContext().getRealPath("/upload/document") + "/" + this.dlFileName;
            File file = new File(url);
            if (!file.exists() || !file.isFile()) {
                return ERROR;
            }
            this.dlFileName = "/upload/document/" + this.dlFileName;
            return SUCCESS;
        } catch (Exception e) {
            return ERROR;
        }

    }

    public String delete() {
        // Case doscase = caseService.findUnique("id=?", new Object[]{caseId});

        boolean fileisok = fileUpDownService.deleteByIdAndTableName(
                caseId, DOCUMENT, FileStorage.getUpLoadPath(ServletActionContext.getRequest()));


        caseService.delById(caseId);
        return SUCCESS;
    }

    public String show() {
        ca = caseService.get(caseId);
        accessoryList = fileUpDownService.getAccessoryByTableNameAndTableIdAndVersion(DOCUMENT, caseId, 0);
        casefillpointsList = casePointsService.find("case_id=?", new Object[]{caseId}, "id");
        if (ca == null) {
            return ERROR;
        }
        return SUCCESS;
    }

    public String update() throws Exception {


        Case ca1 = caseService.get(ca.getId());
        if (ca != null) {

            if (ca.getProduct() > -1) {
                Product p = productService.get(ca.getProduct());
                if (p != null) {
                    ca1.setProduct(ca.getProduct());
                    ca1.setProductName(p.getName());
                     ca1.setProductCode(p.getCode());
                }
            }
            if (ca.getCountry() > -1) {
                Country c = countryService.get(ca.getCountry());
                if (c != null) {
                    ca1.setCountry(ca.getCountry());
                    ca1.setCountryName(c.getName());
                    ca1.setCountryCode(c.getCode());
                }
            }
            ca1.setFillSummy(ca.getFillSummy());

//            Set groupList = new HashSet();
//
//            if (docIdString != null) {
//                String ids[] = docIdString.split(",");
//                for (int i = 0; i < ids.length; i++) {
//                    if (!ids[i].equals("")) {
//                        Document doc = new Document();
//                        doc.setId(new Integer(ids[i]));
//                        groupList.add(doc);
//                    }
//                }
//            }
//            ca.setDocuments(groupList);


            caseService.update(ca1);

//            if (this.getFile() != null) {
//
//                fileUpload(ca);// 调用上传文件方法
//                documentFromatOrderService.createConverOrder(ca.getId());
//            }
            return SUCCESS;

        } else {
            addActionMessage("dc is null!");
            return ERROR;
        }

    }

    public String updateInput() throws Exception {
        actionURI = "update";
        this.createMenus();
        ca = this.caseService.get(caseId);
        if (ca == null) {
            return ERROR;
        } else {
            return SUCCESS;
        }
    }

    public InputStream getInputStream() {

        return ServletActionContext.getServletContext().getResourceAsStream(
                "/" + dlFileName);

    }

    public InputStream getDownloadFile() {
        return ServletActionContext.getServletContext().getResourceAsStream(this.getDlFileName());
    }

    public String getDocIdString() {
        return this.docIdString;
    }

    public void setDocIdString(String docIdString) {
        this.docIdString = docIdString;
    }

    public void createMenus() {
        clist = countryService.createList();
//        productList = productService.findAll();
        proList = documentIndexTreeService.createList();

    }
    private List<CountryObj> clist;

    public List<CountryObj> getClist() {
        return clist;
    }

    public void setClist(List<CountryObj> clist) {
        this.clist = clist;
    }

    public CaseFillPointsService getCasePointsService() {
        return this.casePointsService;
    }

    public void setCasePointsService(CaseFillPointsService casePointsService) {
        this.casePointsService = casePointsService;
    }

    public int getCasePointId() {
        return this.casePointId;
    }

    public void setCasePointId(int casePointId) {
        this.casePointId = casePointId;
    }

    public CaseFillPoints getCasePoints() {
        return this.casePoints;
    }

    public void setCasePoints(CaseFillPoints casePoints) {
        this.casePoints = casePoints;
    }

    //以下是对案例子表的操作（单证附件）
    public String pointslist() throws Exception {

        pageBean = casePointsService.getPageBeanByCaseId(page, pageSize, caseId);
        return SUCCESS;

    }

    public String addPoints() {
        actionURI = "savePoints";
        ca = caseService.get(caseId);
        return SUCCESS;
    }

    public String savePoints() {
        if (casePoints != null) {
            caseId = casePoints.getCaseId();
            String num = StringUtil.getRequestNo();
            casePoints.setNum(num);
            casePointsService.save(casePoints);
            if (this.getFile() != null) {
                casePoints = casePointsService.findUnique("num=?", new Object[]{num});
                fileUpload(casePoints);// 调用上传文件方法
                casePointsService.update(casePoints);
                documentFromatOrderService.createConverOrder(casePoints.getId());
            }
            return SUCCESS;
        } else {
            addActionMessage("dc is null!");
            return ERROR;
        }
    }

    public String viewPoints() throws Exception {
        actionURI = "updatePoints";
        casePoints = casePointsService.get(casePointId);
        accessoryList = fileUpDownService.getAccessoryByTableNameAndTableIdAndVersion(CASEFILLPOINTS, casePointId, 0);
        if (casePoints == null) {
            return ERROR;
        } else {
            return SUCCESS;
        }
    }

    public String updatePoints() throws Exception {
        CaseFillPoints casePointstemp = casePointsService.get(casePoints.getId());
        if (casePoints.getCasepoint() != null && !casePoints.getCasepoint().equals("")) {
            casePointstemp.setCasepoint(casePoints.getCasepoint());
        }
        if (casePoints.getName() != null && !casePoints.getName().equals("")) {
            casePointstemp.setName(casePoints.getName());
        }
        if (casePoints.getDocumentCode() != null && !casePoints.getDocumentCode().equals("")) {
            casePointstemp.setDocumentCode(casePoints.getDocumentCode());
        }
        if (casePoints.getDocumentName() != null && !casePoints.getDocumentName().equals("")) {
            casePointstemp.setDocumentName(casePoints.getDocumentName());
        }
        if (casePoints.getPoints() != null && !casePoints.getPoints().equals("")) {
            casePointstemp.setPoints(casePoints.getPoints());
        }
        if (casePoints.getNote() != null && !casePoints.getNote().equals("")) {
            casePointstemp.setNote(casePoints.getNote());
        }

        this.casePointsService.update(casePointstemp);

//        casePoints = casePointsService.get(casePoints.getId());



        // 删除就附件
        if (delstrings != null && !delstrings.equals("")) {
            String[] delAccessrieStrings = delstrings.split("%");
            for (String s : delAccessrieStrings) {
                boolean fileisok = fileUpDownService.deleteById(Integer.parseInt(s), FileStorage.getUpLoadPath(ServletActionContext.getRequest()));

//                fileUpDownService.delAcessoryByAcessoryId(Integer.parseInt(s));

            }

        }
        if (this.getFile() != null) {
            casePoints = casePointsService.findUnique("num=?", new Object[]{casePointstemp.getNum()});
            fileUpload(casePoints);// 调用上传文件方法
            casePointsService.update(casePoints);
            documentFromatOrderService.createConverOrder(casePoints.getId());
        }


        return SUCCESS;

    }

    public String deletePoints() {
        CaseFillPoints tmp = casePointsService.findUnique("id=?", new Object[]{casePointId});
        if (tmp != null) {
            casePointsService.delById(casePointId);
            boolean fileisok = fileUpDownService.deleteByIdAndTableName(
                    casePointId, CASEFILLPOINTS, FileStorage.getUpLoadPath(ServletActionContext.getRequest()));

        }
        return SUCCESS;
    }
}
